<?php

namespace app\index\service;

use app\common\model\ConsultingComment;
use app\common\model\LawyerImpression;
use app\common\model\Member;
use app\common\model\MemberInfo;
use app\index\dao\ConsultingQuestionDao;
use app\index\dao\MemberDao;
use app\index\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\StringUtil;
use think\Collection;

/**
 * Class LawyerService
 * @package app\lawyer\service
 */
class LawyerService
{
    // dao
    private MemberDao $memberDao;
    private LawyerImpressionService $impressionService;

    public function __construct(MemberDao $memberDao, LawyerImpressionService $impressionService)
    {
        $this->memberDao = $memberDao;
        $this->impressionService = $impressionService;
    }

    /**
     * 律师 列表
     * @param UM|null $user
     * @param $cityId
     * @param $categoryId
     * @param $medal
     * @param $order
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(?UM $user, $cityId, $categoryId, $medal, $kw, $order, ?int $page = null, ?int $page_size = null): Collection
    {
        $userId = $user ? $user->id : 0;

        // 干掉搜索里面的律师两个字
        if (not_blank($kw)) {
            $kw = StringUtil::trim($kw, '律师');
        }

        //这里如果要修改查询，建议把查询放到dao层去
        $collection = $this->memberDao->selectLawyers($cityId, $categoryId, $kw, $order, $page, $page_size);

        // 记录曝光行为
        $collection->each(function (Member $lawyer)use($userId){
            $this->impressionService->insert(LawyerImpression::LVSHI_LIEBIAO, $lawyer->id, $userId);
        });

        return $collection;
    }

    /**
     * 律师主页 查询
     * @param UM|null $user
     * @param int $id
     * @return Member
     */
    public function read(?UM $user, int $id): ?Member
    {
        $record = $this->memberDao->findLawyerHome($id);

        if ($record) {
            // 查询热门咨询
            $questions = $this->getConsultingQuestionDao()->selectLawyerQuestion($id, 5);
            $record->setRelation('questions', $questions);

            // 统计评分分布
            $group_comment = ConsultingComment::where('lawyerId', $id)
                ->field(['level', 'count(*)' => 'number'])
                ->group('level')
                ->order('level', 'DESC')
                ->select();
            $record->setRelation('group_comment', $this->wrapGroupComment($group_comment));
        }

        return $record;
    }

    /**
     * 工作台律师-详情
     * @param UM $user
     * @param int $id
     * @return Member|null
     */
    public function readWorkbench(UM $user, int $id): ?Member
    {
        return $this->memberDao->findLawyerWorkbench($id);
    }

    /**
     * 修改接单状态
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return Member|null
     */
    public function modifyMatchStatus(UM $user, int $id, array $params): ?Member
    {
        params_enums($params, 'matchStatus', 1, 0);

        $record = Member::field(true)->where('id', $id)->find();
        if (!$record) {
            return $record;
        }

        $record->matchStatus = $params['matchStatus'];
        $record->save();

        return $record;
    }

    /**
     * 律师主页设置 - 详情
     * @param UM $user
     * @param int $id
     * @return Member|null
     */
    public function readHomeSetting(UM $user, int $id): ?Member
    {
        return $this->memberDao->findLawyerHomeSetting($id);
    }

    // 律师主页设置 - 保存
    public function modifyHomeSetting(UM $user, int $id, array $params): void
    {
        $memberInfo = $params['memberInfo'] ?? null;
        if (is_null($memberInfo)) {
            return;
        }

        //这里如果要修改查询，建议把查询就放到这里
        $record = MemberInfo::field(true)->where('memberId', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该资料不存在或已被删除');
        }

        $record->indexPic = $memberInfo['indexPic'] ?? '';
        $record->desc = $memberInfo['desc'] ?? '';
        $record->introduce = $memberInfo['introduce'] ?? '';
        $record->save();

        // 保存案件类型
        $record->categories()->sync(ids($memberInfo['categories']));
    }

    private function wrapGroupComment(Collection $group_comment): array
    {

        $max = 5;
        $min = 1;
        $result = [];
        $total = array_sum($group_comment->column('number'));
        $group_comment = $group_comment->column(null, 'level');

        for ($i = $max; $i >= $min; $i--) {
            $number = isset($group_comment[$i]) ? $group_comment[$i]['number'] : 0;

            $temp = [
                'level' => $i,
                'number' => $number,
            ];

            if ($total == 0) {
                $temp['rate'] = 0;
            } else {
                $temp['rate'] = $number / $total;
            }

            $result[] = $temp;
        }

        return $result;
    }

    private function getConsultingQuestionDao(): ConsultingQuestionDao
    {
        return app(ConsultingQuestionDao::class);
    }
}
